/**
 *  文件名:ActivityFeedback.java
 *  修改人:lihangjie
 *  创建时间:2015-8-28 下午12:09:05
 */
package com.sharemob.tinchat.modules.account;

import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;

import com.sharemob.tinchat.R;
import com.sharemob.tinchat.base.BaseActivity;
import com.sharemob.tinchat.base.Callback;
import com.sharemob.tinchat.lib.CircleTimerView;
import com.sharemob.tinchat.lib.Utils;

/**
 * 
 * <一句话功能简述>
 *
 * @author lihangjie
 * version [版本号,2015-8-28 下午12:09:05]
 * @see    [相关类/方法]
 * @since  [产品/模块版本]
 *
 */
public class SignatureVoiceActivity extends BaseActivity {
	private static final String LOG_TAG = "SignatureVoiceActivity";
	 
	private MediaRecorder mRecorder = null;
	private MediaPlayer   mPlayer = null;
	private boolean mStartPlaying = true;
	private ImageButton ib_signatrueVoice;
	private CircleTimerView circleTimerView;
	private String SignatureVoicePath=Utils.getVoiceFilePath();
    private Handler handler=null;
    private Timer timer=null;
    private int ticket=0;
    private int TargetTicket=100;
    private TextView tv_signature_void=null;
    private File signatureVoiceFile=null;
	protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signature_voice);
        
        exitView(R.id.title_back,R.anim.activity_close,0);
        Btn_submit();
        tv_signature_void=(TextView)findViewById(R.id.tv_signatrue_voice_tip);
        circleTimerView=(CircleTimerView)findViewById(R.id.ctv_signatrue_voice);
        ib_signatrueVoice= (ImageButton) findViewById(R.id.ibtn_signatrueVoice);
        
        signatureVoiceFile=new File(SignatureVoicePath);
        if(signatureVoiceFile.exists()){
        	ib_signatrueVoice.setBackgroundResource(R.drawable.btn_signatrue_voice_play);
        	circleTimerView.circleTime(100);
        }else{
        	try {
        		signatureVoiceFile.createNewFile();
        		ib_signatrueVoice.setBackgroundResource(R.drawable.btn_signatrue_voice_recorde);
			} catch (Exception e) {
				e.printStackTrace();
			}
        }
        
        BtnEvent(R.id.btn_recorde, new Callback() {
			public void doDown() {
				if(signatureVoiceFile.exists()){
					signatureVoiceFile.delete();
					circleTimerView.circleTime(0);
					ib_signatrueVoice.setBackgroundResource(R.drawable.btn_signatrue_voice_recorde);
				}
			}
		});
       
        
    	handler = new Handler() {  
            public void handleMessage(Message msg) {  
                super.handleMessage(msg);  
                circleTimerView.circleTime(ticket);
                if(ticket==TargetTicket){
                	ib_signatrueVoice.setBackgroundResource(R.drawable.btn_signatrue_voice_play);
                	onRecord(false);
                	tv_signature_void.setText("");
                }
            }
    	};
        
        ib_signatrueVoice.setOnClickListener(new OnClickListener()
        {
            public void onClick(View v)
            {
            	if(signatureVoiceFile.exists()&&signatureVoiceFile.length()>0){
            		onPlay(mStartPlaying);
            	}else{
            		inithandler();
            		if(timer!=null){
                		onRecord(true);
                	}
            	}
            }
        });
        
    }
    
	private void inithandler(){
    	timer=new Timer();
    	timer.schedule(new TimerTask() {
			public void run() {
				if(ticket<TargetTicket){
					ticket++;
					handler.obtainMessage().sendToTarget();
				}else if(ticket==TargetTicket){
					timer.cancel();
					timer=null;
					ticket=0;
				}
			}
		}, 1000, 100);
    	
    	ib_signatrueVoice.setBackgroundResource(R.drawable.btn_signatrue_voice_stop);
	}
	
    private void onPlay(boolean start) {
        if (start) {
            startPlaying();
            tv_signature_void.setText("在播放中...");
            ib_signatrueVoice.setBackgroundResource(R.drawable.btn_signatrue_voice_stop);
            mStartPlaying=false;
        } else {
            stopPlaying();
            ib_signatrueVoice.setBackgroundResource(R.drawable.btn_signatrue_voice_play);
            mStartPlaying=true;
        }
    }
    
    private void stopRecording() {
        mRecorder.stop();
//        mRecorder.release();
//        mRecorder = null;
    }
    
    private void onRecord(boolean start) {
        if (start) {
        	tv_signature_void.setText("在录音中...");
            startRecording();
        } else {
            stopRecording();
        }
    }
  
    private void startRecording() {
    	 
       mRecorder = new MediaRecorder();
 
//       mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
 
//       mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
 
       mRecorder.setOutputFile(signatureVoiceFile.getAbsolutePath());
 
//       mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
 
       // 从麦克风源进行录音
       mRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
       // 设置输出格式
       mRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
       // 设置编码格式
       mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
 
       try {
 
           mRecorder.prepare();
 
       } catch (IOException e) {
 
           Log.e(LOG_TAG, "prepare() failed");
 
       }
 
 
 
       mRecorder.start();
 
   }
    
    private void startPlaying() {
        mPlayer = new MediaPlayer();
        try {
            mPlayer.setDataSource(signatureVoiceFile.getAbsolutePath());
            mPlayer.prepare();
            mPlayer.start();
            mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {  
                public void onCompletion(MediaPlayer mp) {  
                    stopPlaying();
                    tv_signature_void.setText("");
                    ib_signatrueVoice.setBackgroundResource(R.drawable.btn_signatrue_voice_play);
                }  
            });  
        } catch (IOException e) {
            Log.e(LOG_TAG, "prepare() failed");
        }
    }
  
  
  
    private void stopPlaying() {
    	mPlayer.stop();
//        mPlayer.release();
//        mPlayer = null;
    }
    
    private void Btn_submit(){
        findViewById(R.id.title_submit).setOnClickListener(new OnClickListener()
        {
            public void onClick(View v)
            { 
            	finish();
                overridePendingTransition(0,R.anim.activity_close);
            }
        });
    }
    
	protected void keyEventOfListView(int position, int id) {
		
	}
}
